package com.xinchuang.utils;


import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;


/**
 * @title : TODO
 * @description : (无)
 * <p>
 * Created by Jjddppz On 2020/1/18 11:25
 */
public class ObjectUtil extends ObjectUtils {
    public ObjectUtil() {
    }

    public static boolean isNotEmpty(@Nullable Object obj) {
        return !isEmpty(obj);
    }

    public static Map<String,Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String,Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        for(Field field:clazz.getDeclaredFields()){
            field.setAccessible(true);
            String fileldName = field.getName();
            Object value = field.get(obj);
            map.put(fileldName,value);
        }
        return map;
    }

    public static LinkedHashMap<String,Object> getMapValueForLinkedHashMap(Map obj) {
        LinkedHashMap map = new LinkedHashMap<>();
        if(map==null){
            return map;
        }
        Iterator iterator = obj.keySet().iterator();
        while(iterator.hasNext()){
            Object objKey = iterator.next();
            Object objValue = obj.get(objKey);
            if(objValue instanceof Map){
                map.put(objKey,getMapValueForLinkedHashMap((Map) objValue));
            }else{
                map.put( objKey,objValue);
            }
        }
        return map;

    }

    private static LinkedHashMap getMapValueForLinkedHashMap(Map dataMap,String keyName) {
        LinkedHashMap map = new LinkedHashMap<>();
        if(map==null){
            return map;
        }
        Object valueObj = dataMap.get(keyName);
        if(valueObj instanceof Map){
            Map objMap= (Map) valueObj;
            Iterator iterator = objMap.keySet().iterator();
            while(iterator.hasNext()){
                Object objKey = iterator.next();
                Object objValue = objMap.get(objKey);
                if(objValue instanceof Map){
                    map.put(objKey,getMapValueForLinkedHashMap((Map)objValue));
                }else{
                    map.put(objKey,objValue);
                }
            }
        }
        return map;

    }

}
